package com.hse.gui.ClientComponents;

import com.hse.gui.IClientComponent;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Nosov Alexander
 * Date: 02.06.2009
 * Time: 22:01:05
 * To change this template use File | Settings | File Templates.
 */
public class TempSensorGraphComponent extends JPanel implements IClientComponent {
    public DefaultCategoryDataset dataset;

    public TempSensorGraphComponent() {
// create a dataset...

        Calendar now = Calendar.getInstance();
        dataset = new DefaultCategoryDataset();
// create the chart...
        JFreeChart chart = ChartFactory.createLineChart(
                null, // chart title
                "Time", // domain axis label
                "Temperature", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                false, // include legend
                true, // tooltips
                false // urls
        );
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        ChartPanel chartPanel = new ChartPanel(chart, 400, 300, 300, 200, 1024, 768, true, true, true, true, true, true);
        chartPanel.setDisplayToolTips(false);

// get an axis reference...
        CategoryAxis domainAxis = plot.getDomainAxis();
// change axis properties...
        domainAxis.setCategoryMargin(0);
        domainAxis.setUpperMargin(0);
        ValueAxis valueAxis = plot.getRangeAxis();
        valueAxis.setAutoRange(false);
        valueAxis.setLowerBound(-20);
        valueAxis.setUpperBound(20);

        add(chartPanel);

    }

    public void recv(byte[] data) {

        String currentTemperatureString = new String(data);
        int currentTemperature = Integer.valueOf(currentTemperatureString);

        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        dataset.addValue(currentTemperature, "Classes", dateFormat.format(new Date()));
        if (dataset.getColumnCount() > 10) {
            dataset.removeColumn(0);
        }

    }

    public byte[] send() {
        return new byte[0];  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public String toString() {
        return "Temperature sensor chart";
    }
}
